# models.py
import datetime
from django.db import models
from django.utils import timezone

class Question(models.Model):
    QUESTION_TYPES = (
        ('normal', '普通投票'),
        ('latest', '最新投票'),
        ('hot', '热门投票'),
    )
    
    question_text = models.CharField(max_length=200, verbose_name="问题")
    pub_date = models.DateTimeField(verbose_name="发布日期")
    question_type = models.CharField(
        max_length=10,
        choices=QUESTION_TYPES,
        default='normal',
        verbose_name="问题类型"
    )
    
    def __str__(self):
        return self.question_text
    
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.short_description = "最近发布"
    was_published_recently.boolean = True

    @property
    def total_votes(self):
        """计算该问题的总票数"""
        return sum(choice.votes for choice in self.choices.all())

class Choice(models.Model):
    question = models.ForeignKey(
        Question,
        on_delete=models.CASCADE,
        related_name='choices',
        verbose_name="问题"
    )
    choice_text = models.CharField(max_length=200, verbose_name="选项文本")
    votes = models.IntegerField(default=0, verbose_name="票数")
    
    def __str__(self):
        return self.choice_text

    @property
    def percentage(self):
        """计算该选项的得票百分比"""
        total = self.question.total_votes
        return (self.votes / total * 100) if total > 0 else 0